package com.roadjava.tutor.handler.back;

import com.roadjava.tutor.bean.dto.UserDTO;
import com.roadjava.tutor.bean.enums.RoleEnum;
import com.roadjava.tutor.bean.res.ResultDTO;
import com.roadjava.tutor.bean.vo.UserVO;
import com.roadjava.tutor.service.AdminService;
import com.roadjava.tutor.service.MemberService;
import com.roadjava.tutor.util.Constants;
import com.roadjava.tutor.util.IpUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 会员/管理员 统一入口控制器
 * @author zhaodaowen
 * @see <a href="http://www.roadjava.com">乐之者java</a>
 */
@Controller
public class UserHandler {
    @Resource
    private MemberService memberService;
    @Resource
    private AdminService adminService;
    /**
     * 到登录
     */
    @GetMapping("/toRegister")
    public String toRegister(){
        return "front/register";
    }
    /**
     * 到登录
     */
    @GetMapping("/toLogin")
    public String toLogin(){
        return "front/login";
    }
    /**
     * 注销
     */
    @GetMapping("/logout")
    public String logout(HttpSession httpSession){
        httpSession.invalidate();
        return "redirect:/front/toMain";
    }
    /**
     * 注册
     */
    @PostMapping("/register") @ResponseBody
    public ResultDTO<String> register(UserDTO userDTO){
        String role = userDTO.getRole();
        RoleEnum roleEnum = RoleEnum.getByEnName(role);
        if (roleEnum == null) {
            return ResultDTO.buildFailure("角色不存在");
        }
        return memberService.register(userDTO);
    }
    /**
     * 登录
     */
    @PostMapping("/login")  @ResponseBody
    public ResultDTO<String> login(UserDTO userDTO, HttpServletRequest request){
        String role = userDTO.getRole();
        RoleEnum roleEnum = RoleEnum.getByEnName(role);
        if (roleEnum == null) {
            return ResultDTO.buildFailure("角色不存在");
        }
        userDTO.setIp(IpUtil.getRealIp(request));
        // 校验登录
        ResultDTO<UserVO> resultDTO;
        if (RoleEnum.ADMIN.getEnName().equals(role)) {
            resultDTO = adminService.login(userDTO);
        } else {
            resultDTO = memberService.login(userDTO);
        }
        if (resultDTO.getSuccess()) {
            UserVO data = resultDTO.getData();
            // 设置登录角色
            data.setRole(roleEnum.getCnName());
            request.getSession().setAttribute(Constants.USER_SESSION_KEY,data);
            return ResultDTO.buildSuccess("登录成功");
        }else {
            return ResultDTO.buildFailure(resultDTO.getErrMsg());
        }
    }
}
